﻿using SqlSugar;
using System.Collections.Concurrent;

namespace OnWork.DataCenter.Utils.Caches
{
    /// <summary>
    /// 数据缓存对象
    /// </summary>
    public class SqlSugarCache
    {
        /// <summary>
        /// 静态字典
        /// </summary>
        private static ConcurrentDictionary<string, SqlSugarScope> _DictSqlSugarScope = new ConcurrentDictionary<string, SqlSugarScope>();

        /// <summary>
        /// 获取活创建对象
        /// </summary>
        /// <param name="dbType">数据库类型</param>
        /// <param name="connStr">连接字符串</param>
        /// <param name="dictKey">关键数据库Key</param>
        /// <returns></returns>
        public static SqlSugarScope GetOrCreate(DbType dbType, string connStr, string dictKey)
        {
            //如果字典包含则直接返回
            if (_DictSqlSugarScope.ContainsKey(dictKey))
            {
                var sql = _DictSqlSugarScope[dictKey];
                if (sql != null)
                {
                    return sql;
                }
            }

            if (!string.IsNullOrEmpty(connStr))
            {
                //创建数据库对象
                SqlSugarScope db = new SqlSugarScope(new ConnectionConfig()
                {
                    ConnectionString = connStr,
                    DbType = dbType,
                    IsAutoCloseConnection = true
                });
                _DictSqlSugarScope[dictKey] = db;

                return db;
            }
            return null;
        }

        /// <summary>
        /// 移除全部缓存
        /// </summary>
        public static void RemoveAll()
        {
            _DictSqlSugarScope.Clear();
        }
    }
}